package com.caishi.lkx.common.config;

import cn.hutool.json.JSONObject;
import com.caishi.lkx.common.fliter.ContextInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author by keray
 * date:2021/5/14 4:06 下午
 */
@Configuration
@Slf4j
public class SpringMvcConfig implements WebMvcConfigurer {

    private  ContextInterceptor contextInterceptor;

    @Autowired
    public void WebConfig(ContextInterceptor contextInterceptor) {
        this.contextInterceptor = contextInterceptor;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(MethodParameter methodParameter) {
                return methodParameter.getParameterType().equals(JSONObject.class);
            }

            @Override
            public Object resolveArgument(MethodParameter methodParameter,
                                          ModelAndViewContainer modelAndViewContainer,
                                          NativeWebRequest nativeWebRequest,
                                          WebDataBinderFactory webDataBinderFactory) throws Exception {
                Map<String, String[]> map = nativeWebRequest.getNativeRequest(HttpServletRequest.class).getParameterMap();
                JSONObject jsonObject = new JSONObject();
                for (String key : map.keySet()) {
                    String[] data = map.get(key);
                    if (data == null) continue;
                    if (data.length == 1) {
                        jsonObject.putIfAbsent(key, data[0]);
                    } else if (data.length > 1) {
                        jsonObject.putIfAbsent(key, Arrays.asList(data));
                    }
                }
                return jsonObject;
            }
        });
    }

    @Bean
    @Profile({"dev"})
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(false);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

    @Bean
    @Profile({"daily"})
    public FilterRegistrationBean corsFilter1() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(false);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器并指定拦截的路径
        registry.addInterceptor(this.contextInterceptor)
                .addPathPatterns("/**") // 配置拦截的 URL 路径，可以指定特定的路径
                .excludePathPatterns("/swagger-ui/**", "/v2/api-docs/**"); // 可以排除某些路径
    }

}
